package io.github.godfather1103.macro

import com.intellij.codeInsight.template.*
import com.intellij.psi.PsiDocumentManager
import org.jetbrains.kotlin.idea.liveTemplates.macro.KotlinMacro
import org.jetbrains.kotlin.psi.KtFunction

/**
 * <p>Title:        Godfather1103's Github</p>
 * <p>Copyright:    Copyright (c) 2023</p>
 * <p>Company:      https://github.com/godfather1103</p>
 *
 * @author  作者: Jack Chu E-mail: chuchuanbao@gmail.com
 * @date 创建时间：2023/8/18 13:41
 * @version 1.0
 * @since  1.0
 */
class KotlinFunctionExceptionsMacro : KotlinMacro() {
    override fun getName(): String = "kotlinFunctionExceptions"

    override fun getDefaultValue(): String = "[Exception]"

    override fun getPresentableName(): String = "kotlinFunctionExceptions()"

    override fun calculateResult(params: Array<Expression>, context: ExpressionContext): Result? {
        val project = context.project
        val templateStartOffset = context.templateStartOffset
        val offset = if (templateStartOffset > 0) context.templateStartOffset - 1 else context.templateStartOffset
        PsiDocumentManager.getInstance(project).commitAllDocuments()
        val file = PsiDocumentManager.getInstance(project).getPsiFile(context.editor!!.document) ?: return null
        var place = file.findElementAt(offset)
        while (place != null) {
            if (place is KtFunction) {
                val result = ArrayList<Result>()
                val t = place.annotationEntries.find { it.shortName.toString() == "Throws" }
                t?.valueArguments?.forEach {
                    result.add(TextResult(it.asElement().text.replace("::class", "")))
                }
                return ListResult(result)
            }
            place = place.parent
        }
        return null
    }
}